//
//  AddTaskProcessViewController.m
//  OAProject
//
//  Created by yhj on 2017/3/28.
//  Copyright © 2017年 cdnunion. All rights reserved.
//  添加流程主界面

#import "AddTaskProcessViewController.h"
#import "CommonTableViewCell.h"
#import "SelectContactListViewController.h"
#import "TaskProcessViewController.h"



static NSString *CommonTableViewCellIdentifier=@"CommonTableViewCellIdentifier";

@interface AddTaskProcessViewController ()<UITableViewDelegate,UITableViewDataSource,CuiPickViewDelegate,SelectContactListViewControllerDelegate,UITextFieldDelegate,UITextViewDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSString *endTimeStr;

@property(nonatomic,strong)UIView *headView;

@property(nonatomic,strong)UITextView *textView;

@property(nonatomic,strong)UITextField *nameDetailTF;

@property(nonatomic,strong)NSMutableArray *userNameArr;

@property(nonatomic,strong)NSMutableArray *userIDArr;

@end

@implementation AddTaskProcessViewController

-(UIView *)headView
{
    if (!_headView) {
        _headView=[UIView new];
        _headView=[[UIView alloc]initWithFrame:CGRectMake(0,64,APPW,0)];
        _headView.backgroundColor=WhiteColor;
        setViewHeight_Add(_headView,kmargin*2);

        // 流程标题
        UILabel *nameLabel=[self.headView getLabelWithText:@"流程标题" font:Font_Number(16) textColor:DarkGreyColor textAlignment:NSTextAlignmentLeft lineBreakMode:NSLineBreakByCharWrapping numberOfLines:1];
        [self.headView addSubview:nameLabel];
        nameLabel.frame=CGRectMake(kmargin*2,_headView.frame.size.height,APPW/2,kmargin*2);
        setViewHeight_Add(_headView,kmargin*2+kmargin/2);

        _nameDetailTF=[[UITextField alloc]initWithFrame:CGRectMake(kmargin*2,_headView.frame.size.height,APPW-kmargin*4,kmargin*3)];
        _nameDetailTF.font=Font_Number(16);
        _nameDetailTF.delegate=self;
        _nameDetailTF.textColor=DarkGreyColor;
        // 修改placeholder颜色
        [_nameDetailTF setValue:LightGreyColor forKeyPath:@"_placeholderLabel.textColor"];
//        ViewBorderRadius(_nameDetailTF,kmargin/5,1,MAIN_BACK_COLOR);
        _nameDetailTF.placeholder=@"请输入流程标题";
        [self.headView addSubview:_nameDetailTF];
        setViewHeight_Add(_headView,kmargin*3);


        // 流程描述
        UILabel *projectDesLabel=[self.headView getLabelWithText:@"流程描述" font:Font_Number(16) textColor:DarkGreyColor textAlignment:NSTextAlignmentLeft lineBreakMode:NSLineBreakByCharWrapping numberOfLines:1];
        [self.headView addSubview:projectDesLabel];
        projectDesLabel.frame=CGRectMake(kmargin*2,_headView.frame.size.height+kmargin,APPW/2,kmargin*2);
        setViewHeight_Add(_headView,kmargin*3);

        _textView=[[UITextView alloc]initWithFrame:CGRectMake(kmargin*3/2,_headView.frame.size.height,APPW-kmargin*3,APPH/8)];
//        ViewBorderRadius(_textView,kmargin/5,1,MAIN_BACK_COLOR);
        _textView.delegate=self;
        _textView.font=Font_Number(16);
        _textView.placeholder=@"请输入流程描述";
        _textView.textColor=DarkGreyColor;
        [self.headView addSubview:_textView];
        setViewHeight_Add(_headView,APPH/8+kmargin*2);

        UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(0,_headView.frame.size.height,APPW,kmargin)];
        lineView.backgroundColor=BGColor;
        [self.headView addSubview:lineView];
        setViewHeight_Add(_headView,kmargin);
    }
    return _headView;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title=@"添加流程";

    [AppUI initNavigationItem:self.navigationItem andWithText:@"确  认" andTextColor:WhiteColor andIsRight:YES withBlock:^{

        [self submitService];
    }];

     [self.view addSubview:self.tableView];
}


-(void)submitService
{
     if (self.nameDetailTF.text.length==0)
    {
        [self.view makeToast:@"请输入流程标题" duration:.5 position:CSToastPositionCenter];
    }
    else if (self.textView.text.length==0)
    {
        [self.view makeToast:@"请输入流程描述" duration:.5 position:CSToastPositionCenter];
    }
//    else if ([self.endTimeStr isEqualToString:@"请选择截止时间"])
    else if (self.endTimeStr==nil)
    {
        [self.view makeToast:@"请选择截止时间" duration:.5 position:CSToastPositionCenter];
    }
    else if (self.userIDArr.count==0)
    {
      [self.view makeToast:@"请选择负责人" duration:.5 position:CSToastPositionCenter];
    }
    else
    {
        NSString *fatherID;
        if (self.isFirst==YES)
        {
           fatherID=@"0";
        }
        else
        {
            fatherID=self.model.step_id;
        }

        [API AddTaskProgressWithTaskID:self.taskID title:self.nameDetailTF.text user_ids:self.userIDArr estimateEtime:self.endTimeStr fatherID:fatherID remindMin:@"" description:self.textView.text attachments:@"" success:^(id res) {

            NSLog(@"sdjksdjsdjfd----%@  99----%@",res,res[@"error"]);

            if ([res[@"rt"] isEqual:@(0)])
            {
                [self.view makeToast:res[@"error"] duration:1 position:CSToastPositionCenter];
            }
            else
            {
                [self.view makeToast:@"添加成功" duration:1 position:CSToastPositionCenter];

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:NO];
                });

            }
            
        } failure:^(NSInteger stateCode) {
            
        }];
    }
}

// tableView
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,0,APPW,APPH) style:UITableViewStylePlain];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=MAIN_BACK_COLOR;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.tableFooterView=[UIView new];
        _tableView.tableHeaderView=self.headView;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
        [self.tableView registerClass:[CommonTableViewCell class] forCellReuseIdentifier:CommonTableViewCellIdentifier];
    }
    return _tableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
    {
        CommonTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CommonTableViewCellIdentifier];
        NSString *userNameStr;
        if (self.userIDArr.count==0)
        {
            userNameStr=@"请选择负责人";
        }
        else
        {
            [self.userNameArr componentsJoinedByString:@","];

            if (self.userNameArr.count>1)
            {
                userNameStr=[NSString stringWithFormat:@"%@等",self.userNameArr[0]];
            }
            else
            {
                userNameStr=self.userNameArr[0];
            }
        }
        [cell setCellInfoWithHeaderImage:@"" withTitle:@"负  责  人" withSubTitle:userNameStr withArrow:YES];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.row==1)
    {
        NSString *startTimeStr;
        if (_isFirst==YES)
        {
//           startTimeStr=@"暂无";
            startTimeStr=self.startTimeStr;
        }
        else
        {
            startTimeStr=self.model.estimate_etime;
        }
        CommonTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CommonTableViewCellIdentifier];
        [cell setCellInfoWithHeaderImage:@"" withTitle:@"开始时间" withSubTitle:startTimeStr withArrow:NO];
        cell.arrowImageView.hidden=YES;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    else
    {
        NSString *timeStr;
        if (self.endTimeStr==nil)
        {
            timeStr=@"请选择截止时间";
        }
        else
        {
            timeStr=self.endTimeStr;
        }
        CommonTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CommonTableViewCellIdentifier];
        [cell setCellInfoWithHeaderImage:@"" withTitle:@"截止时间" withSubTitle:timeStr withArrow:YES];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kmargin*5;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if (indexPath.row==0)
    {
        SelectContactListViewController *vc=[SelectContactListViewController new];
        vc.delegate=self;
        [self.navigationController pushViewController:vc animated:NO];
    }
    else if(indexPath.row==2)
    {
        // 选择截止时间
        [self GetEndTime];
    }
}

// delegate
-(void)selectContactUserNameArr:(NSMutableArray *)userNameArr userIDArr:(NSMutableArray *)userIDArr
{
    self.userNameArr=userNameArr;
    self.userIDArr=userIDArr;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
}


// 结束时间
-(void)GetEndTime
{
    CuiPickerView *pickerView=[CuiPickerView new];
    pickerView.frame=CGRectMake(0,APPH,APPW,320);
    pickerView.delegate=self;
    pickerView.backgroundColor=BGColor;
    pickerView.curDate=[NSDate date];
    [self.view addSubview:pickerView];
    [pickerView showInView:self.view];
}

// delegate 刷新数据
-(void)didFinishPickView:(NSString *)date
{
    self.endTimeStr=date;

    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
}


// 间隙置边
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{

    if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

// 点击return键时候键盘下去
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}


@end
